package com.heima.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.entity.AdUser;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginService {

    @Autowired
    private AdUserService adUserService;

    @Autowired
    private BCryptPasswordEncoder encoder;
    /**
     * 登录
     *
     * @param dto
     * @return
     */

    public Map<String, Object> login(AdUserLoginDto dto) {

        String name = dto.getName();
        String password = dto.getPassword();

        //if (StringUtils.isBlank(name)) {
        //    throw new LeadException(AppHttpCodeEnum.PARAM_INVALID);
        //}
        //if (StringUtils.isBlank(password)) {
        //    throw new LeadException(AppHttpCodeEnum.PARAM_INVALID);
        //}

        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName, name);

        AdUser adUser = adUserService.getOne(queryWrapper);
        if (adUser == null) {
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }

        boolean b = encoder.matches(password, adUser.getPassword());

        if (!b) {
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        String token = JwtUtils.generateTokenExpireInMinutes(adUser.getId(), 120);

        HashMap<String, Object> result = new HashMap<>();
        AdUserDto adUserDto = BeanHelper.copyProperties(adUser, AdUserDto.class);
        result.put("user", adUserDto);
        result.put("token", token);
        return result;
    }
}
